package cn.genmer.test.security.recordlog.postprocessor;

import cn.genmer.test.security.recordlog.annotation.ModificationLog;
import cn.genmer.test.security.recordlog.registry.LogDefinitionHolder;
import cn.genmer.test.security.recordlog.util.AopTargetUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;

/**
 * @description: 业务日志 必要参数缓存
 * @author: yyq
 * @date: 2023/8/28 10:43
 */
@Component
public class BizLogBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        Object target = AopTargetUtil.getTarget(bean);
        ReflectionUtils.doWithMethods(target.getClass(), method -> {
            ModificationLog modificationLog = AnnotationUtils.findAnnotation(method, ModificationLog.class);
            if (modificationLog != null) {
                LogDefinitionHolder.forClass(modificationLog.poClazz());
                Field primaryKey = LogDefinitionHolder.getPrimaryKey(modificationLog.poClazz());
                if (primaryKey == null) {
                    throw new IllegalArgumentException("日志配置错误，未检测到主键列: " + modificationLog.poClazz().getName());
                }
                String table = LogDefinitionHolder.getTable(modificationLog.poClazz());
                if (StringUtils.isBlank(table)) {
                    throw new IllegalArgumentException("日志配置错误，未检测到表名: " + modificationLog.poClazz().getName());
                }
            }
        });
        return bean;
    }
}
